<template>
    <div class="role-manage">
        <el-card>
            <template #header>
                <div class="header-bar">
                    <span>角色管理</span>
                    <div>
                        <el-button type="primary" size="small" @click="onAddRole">新增角色</el-button>
                    </div>
                </div>
            </template>
            <el-table :data="tableData" border style="width: 100%; margin-bottom: 16px;" :loading="loading">
                <el-table-column prop="roleName" label="角色名" min-width="120">
                    <template #default="{ row }">
                        <span :class="{ 'no-data': !row.roleName }">{{ row.roleName || '暂无' }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="dataScope" label="数据范围" min-width="120">
                    <template #default="{ row }">
                        <span :class="{ 'no-data': !row.dataScope }">{{ row.dataScope || '暂无' }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="permissionsNames" label="权限" min-width="180">
                    <template #default="{ row }">
                        <template v-if="row.permissionsNames && row.permissionsNames.length">
                            <el-tag v-for="perm in row.permissionsNames" :key="perm" v-bind="getPermTagProps(perm)"
                                class="perm-tag" effect="light">
                                <span style="position: relative; display: inline-block;">
                                    <span v-if="permissionStatusMap[perm] === false"
                                        style="color: #f56c6c; font-size: 20px; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); z-index: 2; pointer-events: none;"
                                        title="该权限已禁用">×</span>
                                    <span style="position: relative; z-index: 1;">{{ perm }}</span>
                                </span>
                            </el-tag>
                        </template>
                        <span v-else class="no-data">暂无</span>
                    </template>
                </el-table-column>
                <el-table-column prop="isActived" label="状态" min-width="80">
                    <template #default="{ row }">
                        <el-tooltip :content="row.isActived ? '点击禁用' : '点击激活'" placement="top">
                            <el-tag :type="row.isActived ? 'success' : 'warning'" style="cursor: pointer"
                                @click="onToggleRoleStatus(row)">
                                {{ row.isActived ? '已激活' : '未激活' }}
                            </el-tag>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column prop="createdAt" label="创建时间" min-width="160">
                    <template #default="{ row }">
                        <span>{{ formatDate(row.createdAt) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="updatedAt" label="更新时间" min-width="160">
                    <template #default="{ row }">
                        <span>{{ formatDate(row.updatedAt) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" min-width="180">
                    <template #default>
                        <el-button type="primary" size="small" disabled>编辑</el-button>
                        <el-button type="danger" size="small" disabled>删除</el-button>
                        <el-button type="warning" size="small" plain disabled>分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination-bar">
                <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="total"
                    :page-size="pageSize" :current-page="pageIndex" :page-sizes="[5, 10, 20, 50, 100]"
                    @size-change="handleSizeChange" @current-change="handlePageChange" />
            </div>
        </el-card>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { roleApi } from '../api/role'
import { permissionApi } from '../api/permission'

function formatDate(date) {
    if (!date) return ''
    return new Date(date).toLocaleString()
}

const tableData = ref([])
const total = ref(0)
const pageIndex = ref(1)
const pageSize = ref(10)
const loading = ref(false)
const permissionStatusMap = ref({})

async function fetchData() {
    loading.value = true
    try {
        const res = await roleApi.getRoles(pageIndex.value, pageSize.value)
        if (res.data.code === 1000) {
            tableData.value = res.data.data.items
            total.value = res.data.data.totalCount
        } else {
            ElMessage.error(res.data.msg || '获取角色数据失败')
        }
    } catch {
        ElMessage.error('获取角色数据失败')
    } finally {
        loading.value = false
    }
}

async function fetchPermissionStatus() {
    const res = await permissionApi.getPermissions(1, 1000)
    if (res.data.code === 1000) {
        permissionStatusMap.value = Object.fromEntries(
            res.data.data.items.map(perm => [perm.permissionName, perm.isActived])
        )
    }
}

function handleSizeChange(val) {
    pageSize.value = val
    pageIndex.value = 1
    fetchData()
}

function handlePageChange(val) {
    pageIndex.value = val
    fetchData()
}

function onAddRole() {
    ElMessage.info('新增角色功能待实现')
}

async function onToggleRoleStatus(row) {
    try {
        let res
        if (row.isActived) {
            res = await roleApi.disableRole(row.id)
        } else {
            res = await roleApi.enableRole(row.id)
        }
        if (res.data.code === 1000) {
            ElMessage.success(res.data.msg || '操作成功')
            fetchData()
        } else {
            ElMessage.error(res.data.msg || '操作失败')
        }
    } catch {
        ElMessage.error('操作失败')
    }
}

// 权限类型与颜色映射
const permTypeMap = [
    { keyword: '读', type: 'info' },
    { keyword: '写', type: 'success' },
    { keyword: '管理', type: 'warning' },
    { keyword: '审批', type: 'danger' },
    { keyword: '修改', type: '', color: '#e8f3ff', textColor: '#409EFF' }, // 浅蓝底蓝字
    { keyword: '删除', type: '', color: '#fde2e2', textColor: '#F56C6C' }, // 浅红底红字
    // 可根据实际权限名继续扩展
]
function getPermTagType(perm) {
    const found = permTypeMap.find(item => perm.includes(item.keyword))
    return found ? found.type : 'default'
}

function getPermTagProps(perm) {
    if (permissionStatusMap[perm] === false) {
        return {
            type: 'info',
            color: '#f4f4f5',
            style: { color: '#b1b3b8', 'border-color': '#ebeef5', position: 'relative' }
        }
    }
    const type = getPermTagType(perm)
    return type && ['primary', 'success', 'info', 'warning', 'danger'].includes(type)
        ? { type }
        : {}
}

onMounted(() => {
    fetchPermissionStatus()
    fetchData()
})
</script>

<style scoped>
.role-manage {
    max-width: 1200px;
    margin: 20px auto;
}

.header-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.perm-tag {
    margin-right: 4px;
}

.no-data {
    color: #c0c4cc;
    font-style: italic;
}

.pagination-bar {
    margin-top: 16px;
    text-align: right;
}
</style>